<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="top-panel">
      <view class="header">
        <u-icon name="arrow-left" size="40" color="#333" @click="goBack" class="back-button"></u-icon>
        <text class="title">支付页面</text>
      </view>
    </view>

    <!-- 支付信息 -->
    <view class="pay-info">
      <view class="detail-item">
        <text class="label">订单号：</text>
        <text class="value">{{ orderDetail.outTradeNo || '未知订单' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">套餐名称：</text>
        <text class="value">{{ orderDetail.packageName || '加载中...' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">医院名称：</text>
        <text class="value">{{ orderDetail.hospitalName || '加载中...' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">就诊人：</text>
        <text class="value">{{ orderDetail.patientName || '加载中...' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">预约时间：</text>
        <text class="value">{{ orderDetail.appointmentTime || '未设置' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">订单金额：</text>
        <text class="value">¥{{ orderDetail.totalAmount || '0.00' }}</text>
      </view>
      <view class="detail-item">
        <text class="label">订单状态：</text>
        <text class="value" :style="{ color: getStatusColor(orderDetail.status) }">
          {{ orderDetail.status || '待支付' }}
        </text>
      </view>
    </view>

    <!-- 去支付按钮 -->
    <view class="fixed-bottom">
      <button class="pay-btn" :disabled="orderDetail.status !== '待支付'" @click="submitPay">去支付</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      outTradeNo: '', // 从参数获取订单号
      orderDetail: {}, // 订单详情
      isLoading: false, // 加载状态
      userId: null,  // 用户ID
    };
  },
  onLoad(options) {
    let userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.id) {
      this.userId = userInfo.id;
    } else {
      console.warn('未找到用户ID，跳转到登录页面');
      this.userId = '1'; // 兜底值，仅用于测试
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/public/login' });
          }, 2000);
        }
      });
    }

    this.outTradeNo = options.outTradeNo || '未知订单';
    this.orderDetail = {
      outTradeNo: this.outTradeNo,
      totalAmount: options.totalAmount || '0.00',
      status: options.status || '待支付',
      packageId: options.packageId || null,
      hospitalId: options.hospitalId || null,
      patientId: options.patientId || null,
      appointmentTime: options.appointmentTime || new Date().toISOString().split('T')[0],
      packageName: decodeURIComponent(options.packageName || ''),
      hospitalName: decodeURIComponent(options.hospitalName || ''),
      patientName: decodeURIComponent(options.patientName || '')
    };
    // 仅在必要时获取额外信息
    this.fetchAdditionalDetailsIfNeeded();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    // 仅在缺少数据时获取额外信息
    fetchAdditionalDetailsIfNeeded() {
      this.isLoading = true;
      const promises = [];

      // 如果套餐名称缺失，查询套餐详情
      if (!this.orderDetail.packageName && this.orderDetail.packageId) {
        promises.push(
            new Promise((resolve, reject) => {
              uni.request({
                url: `http://localhost:8080/app/physical/detail/${this.orderDetail.packageId}`,
                method: 'GET',
                success: (res) => {
                  if (res.data.code === 200 && res.data.data) {
                    this.orderDetail.packageName = res.data.data.packageName || '未知套餐';
                    this.orderDetail.hospitalName = res.data.data.hospitalName || this.orderDetail.hospitalName;
                  } else {
                    this.orderDetail.packageName = '未知套餐';
                  }
                  resolve();
                },
                fail: (err) => {
                  this.orderDetail.packageName = '未知套餐';
                  reject(err);
                }
              });
            })
        );
      }

      // 如果就诊人名称缺失，查询就诊人列表
      if (!this.orderDetail.patientName && this.orderDetail.patientId) {
        promises.push(
            new Promise((resolve, reject) => {
              uni.request({
                url: 'http://localhost:8080/app/hospital/patient/list',
                method: 'GET',
                success: (res) => {
                  if (res.data.code === 200 && res.data.rows) {
                    const patient = res.data.rows.find(item => item.id === this.orderDetail.patientId);
                    this.orderDetail.patientName = patient ? patient.name : '未知就诊人';
                  } else {
                    this.orderDetail.patientName = '未知就诊人';
                  }
                  resolve();
                },
                fail: (err) => {
                  this.orderDetail.patientName = '未知就诊人';
                  reject(err);
                }
              });
            })
        );
      }

      // 如果医院名称缺失，查询医院详情
      if (!this.orderDetail.hospitalName && this.orderDetail.hospitalId) {
        promises.push(
            new Promise((resolve, reject) => {
              uni.request({
                url: `http://localhost:8080/app/hospital/detail/${this.orderDetail.hospitalId}`,
                method: 'GET',
                success: (res) => {
                  if (res.data.code === 200) {
                    this.orderDetail.hospitalName = res.data.data.name || '未知医院';
                  } else {
                    this.orderDetail.hospitalName = '未知医院';
                  }
                  resolve();
                },
                fail: (err) => {
                  this.orderDetail.hospitalName = '未知医院';
                  reject(err);
                }
              });
            })
        );
      }

      Promise.all(promises).then(() => {
        this.isLoading = false;
        this.$forceUpdate();
      }).catch(err => {
        console.error('获取额外信息失败:', err);
        this.isLoading = false;
      });
    },
    // 提交支付请求
    submitPay() {
      if (this.orderDetail.status !== '待支付') {
        uni.showToast({
          title: '订单状态不支持支付',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '确认支付',
        content: `您将支付 ¥${this.orderDetail.totalAmount}，是否确认？`,
        success: (res) => {
          if (res.confirm) {
            this.handlePayRequest();
          } else {
            console.log('用户取消支付');
          }
        }
      });
    },
    // 发起支付请求
    handlePayRequest() {
      console.log('开始发起支付请求:'+this.userId)
      const orderData = {
        userId: this.userId,
        outTradeNo: this.orderDetail.outTradeNo,
        packageId: this.orderDetail.packageId ? this.orderDetail.packageId.toString() : null,
        hospitalId: this.orderDetail.hospitalId ? this.orderDetail.hospitalId.toString() : null,
        patientId: this.orderDetail.patientId ? this.orderDetail.patientId.toString() : null,
        packagePrice: this.orderDetail.totalAmount ? this.orderDetail.totalAmount.toString() : '0.00',
        date: this.orderDetail.appointmentTime || new Date().toISOString().split('T')[0]
      };

      uni.request({
        url: 'http://localhost:8080/app/physical/pay',
        method: 'POST',
        data: orderData,
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          console.log('支付请求成功，返回数据:', res);
          if (res.statusCode === 200 && res.data) {
            // 解析并提交支付宝表单
            this.handlePayForm(res.data);
          } else {
            uni.showToast({
              title: '支付请求失败，状态码: ' + res.statusCode,
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.log('支付请求失败:', err);
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    // 处理支付宝支付表单并跳转
    handlePayForm(formData) {
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = formData;
      const form = tempDiv.querySelector('form');
      if (form) {
        document.body.appendChild(form);
        form.submit();
      } else {
        uni.showToast({
          title: '支付表单解析失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 根据状态返回颜色
    getStatusColor(status) {
      switch (status) {
        case '待支付':
          return '#FF4444';
        case '已支付':
          return '#00AA00';
        case '已取消':
          return '#999999';
        default:
          return '#333333';
      }
    },
  }
};
</script>

<style>
.container {
  padding: 20rpx;
  padding-bottom: 120rpx;
  height: 100vh;
  overflow: auto;
}

.top-panel {
  background-color: #fff;
  padding: 10rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.back-button {
  position: absolute;
  left: 10rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.pay-info {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 10rpx;
  margin-top: 20rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.label {
  color: #666;
  font-size: 28rpx;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.pay-btn {
  background: #007AFF;
  color: white;
  font-size: 32rpx;
  padding: 0 60rpx;
  border-radius: 50rpx;
  line-height: 2.2;
}

.pay-btn[disabled] {
  background: #cccccc;
}
</style>